/**
 * 引用外部JS
 * @param {} path JS的相对路径
 */
function getScript(path) {
    document.write('<script type="text/javascript" src="' + window.rootPath + "/" + path + window.resVersion + '"></script>');
}
/**
 * 引用外部CSS
 * @param {} path CSS的相对路径
 */
function getLink(path) {
    document.write('<link type="text/css" rel="stylesheet" href="' + window.rootPath + "/" + path + window.resVersion + '" />');
}
/**
 * 引入翻译显示JS
 * @param {} types
 */
function display(types){
    document.write('<script type="text/javascript" src="' + window.basePath + "/display.js?type=" + encodeURIComponent(types) + "&v=" + new Date() + '"></script>');
}

function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return '';
    }
    if (bytes >= 1024 * 1024 * 1024) {
        return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    }
    if (bytes >= 1024 * 1024) {
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }
    return (bytes / 1024).toFixed(2) + ' KB';
}

function cutText(str, len, ext, label, attr) {
	if(!str){
		return null;
	}
	var s = "";
	if(str && str.length > len){
		s += "<"+label+" title='"+str+"' "+attr+">";
		s += str.substring(0, len - ext.length) + ext;
	}else{
		s += "<"+label+" "+attr+">";
		s += str;
	}
	s += "</"+label+">";
	return s;
}

Number.prototype.toPercent = function(){
    return (Math.round(this * 10000)/100).toFixed(2) + '%';
};
(function($){
    var randomList = {};
    /*生产随机数*/
    function getRandom(length){
        length = length ? length : 8;
        var str;
        while(true){
            str = Math.random().toString().substr(2, length);
            if(!randomList[str]){
                randomList[str] = null;
                break;
            }
        }
        return str;
    }
    
    function error(msg) {
        if (window.console && window.console.error) {
            window.console.error(msg);
        } else if (window.opera && window.opera.postError) {
            window.opera.postError(msg);
        }
    }
    
    /*Dom加载完成之后调用*/
    $(function(){
        $.ajaxSetup({cache:false,error:function(XMLHttpRequest, textStatus, errorThrown){
            if(textStatus == 'timeout' || textStatus == 'error'){
                error('请求错误','AJAX请求失败~[请检查网络]','error');
            } else {
                error('请求错误','AJAX请求错误~','error');
            }
            /*log('AJAX请求超时~');*/
        },dataFilter:function(data,type){
            return data;
        },statusCode:{
            404:function(){error('请求错误','请求路径错误~','error');},
            302:function(){error('请求错误','用户登录失效~','error');},
            500:function(){error('请求错误','服务端出现异常~','error');}
        }/*,beforeSend:function(XMLHttpRequest){
        	// 开始AJAX
        },complete:function(XMLHttpRequest, textStatus){
            // 完成AJAX
        }*/});
        
        if($('a.nav-header').length) {
            $('a.nav-header').click(function(){
                $(this).parent().toggleClass('active');
                $(this).next().animate({height: 'toggle', opacity: 'show'}, "normal");
            });
            var pId = $('a.active').attr('pId');
            if(pId) {
            	$('#nav-one-' + pId).addClass('active').children('ul').show();
            }
        }
        
        /**IE8 placeholder属性*/
        if (!$.support.leadingWhitespace) {
    		$('input, textarea').placeholder();
    	}
    });
    function ajaxRequest(url, params, callback, type, dataType) {
        $.ajax({
            dataType:type ? type : 'json',
            url:url,
            data:params,
            cache:false,
            type:dataType,
            success:callback
        });
    }
    /*jQuery插件$.method(params1, params2, ...)*/
    $.extend({
        _ajaxPost:function(url, params, callback, type){
            ajaxRequest(url, params, callback, type, 'POST');
        },
        _ajaxGet:function(url, params, callback, type){
            ajaxRequest(url, params, callback, type, 'GET');
        },
        formatDate: function formatDate(date, format) {
            var weeks = ['日', '一', '二', '三', '四', '五', '六'];
            return format.replace(/YYYY|MM|DD|hh|mm|ss|星期/g, function(a) {
                switch (a) {
                    case 'YYYY' :
                        return date.getFullYear();
                    case 'MM' :
                        return ((date.getMonth() + 1 < 10) ? '0' : '') + (date.getMonth() + 1);
                    case 'DD' :
                        return (date.getDate() < 10 ? '0' : '') + date.getDate();
                    case 'hh' :
                        return (date.getHours() < 10 ? '0' : '') + date.getHours();
                    case 'mm' :
                        return (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
                    case 'ss' :
                        return (date.getSeconds() < 10 ? '0' : '') + date.getSeconds();
                    case '星期' :
                        return '星期' + weeks[date.getDay()];
                }
            });
        },
        _dialog:function(options){
            var defaults = {
                resize:false,
                lock:true,
                opacity:0,
                through:false
                };
            $.extend(defaults, options || {});
            if(defaults.through){
                art.dialog.through(defaults);
            } else {
                $.dialog(defaults);
            }
        },
        modalDialog: function (option){
            $('#'+option.id).find('.modal-title').eq(0).html(option.title);
            if(typeof option.ok === 'function'){
                $('#'+option.id).find('.btn-primary').eq(0).unbind("click").click(option.ok);
            }
            $('#'+option.id).modal().css();
        },
        modalConfirm: function (option){
            $('#'+option.id).find('.modal-body').eq(0).html(option.content);
            if(typeof option.ok === 'function'){
                $('#'+option.id).find('.btn-primary').eq(0).unbind("click").click(option.ok);
            }
            $('#'+option.id).modal().css();
        }
    });
    /* jQuery插件$(select).method(params1, params2, ...) */
    $.fn.extend({
        _jsonToForm:function(json){
            var form = $(this);
            if($.isPlainObject(json)){
                $.each(json,function(i,n){
                    var field = form.find('input[name='+i+']');
                    switch (field.attr('type')) {
                    case 'hidden':
                        field.val(n);
                        break;
                    case 'text':
                        field.val(n);
                        break;
                    case 'radio':
                        field.each(function(){
                            var value = $(this).val();
                            if(value == 'true'){value = true;}else if(value == 'false'){value = false;}
                            if(value == n){$(this).get(0).checked = true;}
                            });
                        break;
                    case 'checkbox':
                        field.each(function(){
                            var value = $(this).val();
                            if(value == 'true'){value = true;}else if(value == 'false'){value = false;}
                            if(value == n){$(this).get(0).checked = true;}
                        });
                        break;
                    default:
                        field = form.find('select[name='+i+']');
                        if(!$.isEmptyObject(field.get(0))){
                            field.children('option').each(function(){
                                if($(this).val() == n){this.selected = true;}
                            });
                        }
                        field = form.find('textarea[name='+i+']');
                        if(!$.isEmptyObject(field.get(0))){
                            field.val(n);
                        }
                        break;
                    }
                });
            }
        },_formToJson:function(){
            var str = $(this).serialize();
                str = str.replace(/\+/g,"%20");
                str = str.replace(/&/g,"\",\"");
                str = str.replace(/=/g,"\":\"");
            var data = eval("({\""+str +"\"})");
            $.each(data,function(i,n){data[i] = $.trim(decodeURIComponent(n));});
            return data; 
        },_ajaxForm:function(callback){
            var target = $(this);
            if($.isEmptyObject($('#ajaxFormResultTip').get(0))){$('body').append('<div id="ajaxFormResultTip" style="display: none;"></div>');}
            var options = {target:'#ajaxFormResultTip',url:$(this).attr('action'),type:'POST',beforeSubmit:function(){
                var submit = target.data('submit') ? false : true;
                target.data('submit', true);
                if(!submit) {
                    asyncbox.tips('不可重复提交表单！', 'error');
                }
                return submit;
            },success: function(){
                if(typeof callback === 'function'){
                    try {
                        callback(eval('('+$('#ajaxFormResultTip').text()+')'));
                    } catch (e) {
                    	asyncbox.tips('AJAX请求返回数据解析错误~', 'error');
                        error('AJAX请求返回数据解析错误~['+e.message+']');
                    }
                }
            }, complete : function(){
                target.data('submit', false);
            }};
            $(this).ajaxSubmit(options);
        },
        _clip:function(){
        	ZeroClipboard.config({moviePath: window.rootPath + '/assets/common/zeroclipboard/ZeroClipboard.swf'});
            var clip = new ZeroClipboard($(this));
            clip.on("load", function (client) {
                client.on("complete", function (client, args) {
                  alert('复制成功！');
                });
            });
            clip.on("noFlash", function (client) {
                alert("Your browser has no Flash.");
            });
            clip.on("wrongFlash", function (client, args) {
                alert("Flash 10.0.0+ is required but you are running Flash " + args.flashVersion.replace(/,/g, "."));
            });
        },
        preview: function() {
            var xOffset = 10, yOffset = 20, w = $(window).width();
            $(this).each(function () {
                $(this).hover(function (e) {
                    var title = $(this).attr('title');
                    if (/.png$|.gif$|.jpe?g$|.bmp$/.test($(this).attr("href"))) {
                        $("body").append("<div id='preview'><div><img src='" + $(this).attr('href') + "' />" + (!title ? "" : ("<p>" + title + "</p>")) + "</div></div>");
                    } else {
                        $("body").append("<div id='preview'><div>" + (!title ? "" : ("<p>" + title + "</p>")) + "</div></div>");
                    }
                    $("#preview").css({ position: "absolute", padding: "3px", border: "1px solid #CCCCCC", backgroundColor: "#EEEEEE", top: (e.pageY - yOffset) + "px", zIndex: 1000});
                    $("#preview > div").css({padding: "2px", backgroundColor: "white", border: "1px solid #CCCCCC"});
                    $("#preview > div > p").css({ textAlign: "center", fontSize: "12px", padding: "8px 0 3px", margin: "0"});
                    if (e.pageX < w / 2) {
                        $("#preview").css({left: e.pageX + xOffset + "px", right: "auto"}).fadeIn("fast");
                    } else {
                        $("#preview").css("right", (w - e.pageX + yOffset) + "px").css("left", "auto").fadeIn("fast");
                    }
                }, function () {
                    $("#preview").remove();
                }).mousemove(function (e) {
                    $("#preview").css("top", (e.pageY - xOffset) + "px");
                    if (e.pageX < w / 2) {
                        $("#preview").css("left", (e.pageX + yOffset) + "px").css("right", "auto");
                    } else {
                        $("#preview").css("right", (w - e.pageX + yOffset) + "px").css("left", "auto");
                    }
                });
            });
        }
    });
    
    /* 设置datatable默认值初始化 */
    $.extend( true, $.fn.dataTable.defaults, {
    	"autoWidth"        : false,
        "bSort"            : false,
        "bFilter"          : false,
        "processing"       : true,
        "serverSide"       : true,
        "iDisplayLength"   : 20,
        "aLengthMenu"      : [20, 30, 50, 100],
        "sDom"             : "<''r>t<'row'<'col-md-5 col-sm-12'li><'col-md-7 col-sm-12'p>>",
        "fnServerData"     : function(sSource, aoData, fnCallback) {$.ajax({"dataType" : 'json', "type" : "POST", "url" : sSource, "data" : aoData, "success" : fnCallback})},
        "oLanguage"        : {"sLengthMenu": "每页 _MENU_ 条", "sProcessing": "正在加载数据...", "sInfo": "从 _START_ 到 _END_(共 _MAX_ 条数据)", "sInfoEmpty": "没有数据", "sInfoFiltered": "(共 _MAX_ 条数据)", "oPaginate": {"sFirst": "首页", "sPrevious": "前一页", "sNext": "后一页", "sLast": "尾页"}, "sZeroRecords": "没有检索到数据", sEmptyTable:"没有检索到数据"}
    });
    /* 查询拓展 */
    $.fn.dataTableExt.oApi._fnAjaxReload = function(oSettings, sNewSource, fnCallback, bStandingRedraw){
         oSettings._iDisplayStart = 0;
        this.oApi._fnAjaxUpdate(oSettings);
    };
})(jQuery);